package cn.yangyumanage.adapter;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.flexbox.FlexboxLayout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import cn.yangyumanage.R;
import cn.yangyumanage.application.DataApplication;
import cn.yangyumanage.bean.LargeClassification;
import cn.yangyumanage.bean.SmallClassification;
import cn.yangyumanage.bean.TheRegion;
import cn.yangyumanage.bean.TheYear;
import cn.yangyumanage.callback.DataCallBack;
import cn.yangyumanage.http.HttpClient;
import cn.yangyumanage.model.TagAllocationHttpModel;
import cn.yangyumanage.util.ToastUtil;
import cn.yangyumanage.util.Utils;

public class TagAllocationRvAdapter extends RecyclerView.Adapter<TagAllocationRvAdapter.MyViewHolder> {
    private final Context context;

    private final List<LargeClassification> largeClassifications = new ArrayList<>();
    private final TagAllocationHttpModel httpModel = new TagAllocationHttpModel();
    private AlertDialog.Builder builder;

    public TagAllocationRvAdapter(Context context) {
        this.context = context;
        builder = new AlertDialog.Builder(context);
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setData(List<LargeClassification> largeClassificationList) {
        largeClassifications.addAll(largeClassificationList);
        notifyDataSetChanged();
    }

    public void clearAllData() {
        largeClassifications.clear();
    }

    @NonNull
    @Override
    public TagAllocationRvAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.tag_allocation_rv_item, parent, false);
        return new MyViewHolder(view);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull TagAllocationRvAdapter.MyViewHolder holder, @SuppressLint("RecyclerView") int position) {
        holder.tv_large_classification.setText(largeClassifications.get(position).getClassification() + ":");
        getAllRelatedSmallClassification(largeClassifications.get(position).getId(), holder.fl_small);
        getAllRelatedRegion(largeClassifications.get(position).getId(), holder.fl_region);
        getAllRelatedYear(largeClassifications.get(position).getId(), holder.fl_year);
    }

    @Override
    public int getItemCount() {
        return largeClassifications.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {


        private final TextView tv_large_classification;
        private final FlexboxLayout fl_small;
        private final FlexboxLayout fl_region;
        private final FlexboxLayout fl_year;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_large_classification = itemView.findViewById(R.id.tv_large_classification);
            fl_small = itemView.findViewById(R.id.fl_small);
            fl_region = itemView.findViewById(R.id.fl_region);
            fl_year = itemView.findViewById(R.id.fl_year);
        }
    }

    private void show(int largeId, Integer id, String value, String description, FlexboxLayout flexboxLayout, String tag) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.tag_item, flexboxLayout, false);
        TextView tv_id = itemView.findViewById(R.id.tv_id);
        tv_id.setText(String.valueOf(id));
        TextView tv_item = itemView.findViewById(R.id.tv_item);
        tv_item.setText(value);
        ImageView iv_delete = itemView.findViewById(R.id.iv_delete);
        iv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String contentStr = tv_item.getText().toString();
                builder.setTitle(null);
                builder.setMessage("真的要删除" + description + "“ " + contentStr + " ”吗？");
                builder.setPositiveButton("取消", null);
                builder.setNegativeButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String id = tv_id.getText().toString();
                        switch (tag) {
                            case "小分类":
                                deleteSmallClassificationRelation(largeId, Integer.parseInt(id), flexboxLayout);
                                break;
                            case "地区":
                                deleteRegionRelation(largeId, Integer.parseInt(id), flexboxLayout);
                                break;
                            case "年份":
                                deleteYearRelation(largeId, Integer.parseInt(id), flexboxLayout);
                                break;
                        }
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
                dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.RED);
            }
        });
        flexboxLayout.addView(itemView);
    }

    private void add(int id, FlexboxLayout flexboxLayout, String description, String tag, Object data) {
        View addBtnView = LayoutInflater.from(context).inflate(R.layout.add_button_item, flexboxLayout, false);
        LinearLayout ll_add_item = addBtnView.findViewById(R.id.ll_add_item);
        ll_add_item.setOnClickListener(new View.OnClickListener() {

            private ColorStateList blueColorStateList = AppCompatResources.getColorStateList(context, R.color.blue);

            @Override
            public void onClick(View v) {
                View view = View.inflate(context, R.layout.tag_allocation_dialog, null);
                LinearLayout ll_tag_allocation_dialog = view.findViewById(R.id.ll_tag_allocation_dialog);
                TextView tv_no_one_to_add = view.findViewById(R.id.tv_no_one_to_add);
                List<CheckBox> checkBoxes = new ArrayList<>();
                switch (tag) {
                    case "小分类":
                        List<SmallClassification> smallClassificationList = Utils.<SmallClassification>objectToList(data);
                        getAllSmall(smallClassificationList, ll_tag_allocation_dialog, checkBoxes, tv_no_one_to_add);
                        break;
                    case "地区":
                        List<TheRegion> theRegionList = Utils.<TheRegion>objectToList(data);
                        getAllRegion(theRegionList, ll_tag_allocation_dialog, checkBoxes, tv_no_one_to_add);
                        break;
                    case "年份":
                        List<TheYear> theYearList = Utils.<TheYear>objectToList(data);
                        getAllYear(theYearList, ll_tag_allocation_dialog, checkBoxes, tv_no_one_to_add);
                        break;
                }
                builder.setTitle(description + "添加");
                builder.setMessage(null);
                builder.setPositiveButton("添加", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (tag) {
                            case "小分类":
                                for (CheckBox checkBox : checkBoxes) {
                                    if (checkBox.isChecked()) {
                                        addSmallClassificationRelation(flexboxLayout, id, checkBox.getId());
                                    }
                                }
                                break;
                            case "地区":
                                for (CheckBox checkBox : checkBoxes) {
                                    if (checkBox.isChecked()) {
                                        addRegionRelation(flexboxLayout, id, checkBox.getId());
                                    }
                                }
                                break;
                            case "年份":
                                for (CheckBox checkBox : checkBoxes) {
                                    if (checkBox.isChecked()) {
                                        addYearRelation(flexboxLayout, id, checkBox.getId());
                                    }
                                }
                                break;
                        }
                    }
                });
                builder.setNegativeButton("取消", null);
                AlertDialog dialog = builder.create();
                dialog.setView(view);
                dialog.show();
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(blueColorStateList);
            }
        });
        flexboxLayout.addView(addBtnView);
    }

    //获取指定大分类id所关联的所有小分类
    public void getAllRelatedSmallClassification(int id, FlexboxLayout flexboxLayout) {
        httpModel.getAllRelatedSmallClassification(id, new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<SmallClassification> datas = Utils.<SmallClassification>objectToList(data);
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        flexboxLayout.removeAllViews();
                        for (SmallClassification smallClassification : datas) {
                            show(id, smallClassification.getId(), smallClassification.getClassification(), "类型", flexboxLayout, "小分类");
                        }
                        add(id, flexboxLayout, "类型", "小分类", datas);
                    }
                });
            }
        });
    }

    //获取指定大分类id所关联的所有地区
    public void getAllRelatedRegion(int id, FlexboxLayout flexboxLayout) {
        httpModel.getAllRelatedRegion(id, new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<TheRegion> datas = Utils.<TheRegion>objectToList(data);
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        flexboxLayout.removeAllViews();
                        for (TheRegion theRegion : datas) {
                            show(id, theRegion.getId(), theRegion.getTheRegion(), "地区", flexboxLayout, "地区");
                        }
                        add(id, flexboxLayout, "地区", "地区", datas);
                    }
                });
            }
        });
    }

    //获取指定大分类id所关联的所有年份
    public void getAllRelatedYear(int id, FlexboxLayout flexboxLayout) {
        httpModel.getAllRelatedYear(id, new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<TheYear> datas = Utils.<TheYear>objectToList(data);
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        flexboxLayout.removeAllViews();
                        for (TheYear theYear : datas) {
                            show(id, theYear.getId(), theYear.getTheYear(), "年份", flexboxLayout, "年份");
                        }
                        add(id, flexboxLayout, "年份", "年份", datas);
                    }
                });
            }
        });
    }

    //给指定大分类添加指定小分类的关联
    public void addSmallClassificationRelation(FlexboxLayout flexboxLayout, int largeId, int smallId) {
        httpModel.addSmallClassificationRelation(largeId, smallId, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Boolean flag = (Boolean) data;
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (flag) {
                            getAllRelatedSmallClassification(largeId, flexboxLayout);
                            DataApplication.classificationAndImageQualityFlag = false;
                        } else {
                            ToastUtil.show(context, "添加失败");
                        }
                    }
                });
            }
        });
    }

    //删除指定大分类和小分类的关联
    public void deleteSmallClassificationRelation(int largeId, int smallId, FlexboxLayout flexboxLayout) {
        httpModel.deleteSmallClassificationRelation(largeId, smallId, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Boolean flag = (Boolean) data;
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (flag) {
                            getAllRelatedSmallClassification(largeId, flexboxLayout);
                            DataApplication.classificationAndImageQualityFlag = false;
                        } else {
                            ToastUtil.show(context, "删除失败");
                        }
                    }
                });
            }
        });
    }

    //获取所有小分类
    private void getAllSmall(List<SmallClassification> rdatas, LinearLayout layout, List<CheckBox> checkBoxes, TextView textView) {
        httpModel.getAllSmall(data -> {
            List<SmallClassification> datas = Utils.<SmallClassification>objectToList(data);
            Iterator<SmallClassification> iterator = datas.iterator();
            while (iterator.hasNext()) {
                SmallClassification oneData = iterator.next();
                for (SmallClassification rdata : rdatas) {
                    if (Objects.equals(rdata.getClassification(), oneData.getClassification())) {
                        iterator.remove();
                    }
                }
            }
            ContextThemeWrapper contextThemeWrapper = new ContextThemeWrapper(context, R.style.CheckBox);
            HttpClient.handler.post(new Runnable() {
                @Override
                public void run() {
                    if (datas.size() == 0) {
                        textView.setVisibility(View.VISIBLE);
                    }
                    for (SmallClassification smallClassification : datas) {
                        CheckBox checkBox = new CheckBox(contextThemeWrapper);
                        checkBox.setText(smallClassification.getClassification());
                        checkBox.setId(smallClassification.getId());
                        checkBoxes.add(checkBox);
                        layout.addView(checkBox);
                    }
                }
            });
        });
    }

    //给指定大分类添加指定地区的关联
    public void addRegionRelation(FlexboxLayout flexboxLayout, int largeId, int regionId) {
        httpModel.addRegionRelation(largeId, regionId, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Boolean flag = (Boolean) data;
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (flag) {
                            getAllRelatedRegion(largeId, flexboxLayout);
                            DataApplication.classificationAndImageQualityFlag = false;
                        } else {
                            ToastUtil.show(context, "添加失败");
                        }
                    }
                });
            }
        });
    }

    //删除指定大分类和地区的关联
    public void deleteRegionRelation(int largeId, int regionId, FlexboxLayout flexboxLayout) {
        httpModel.deleteRegionRelation(largeId, regionId, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Boolean flag = (Boolean) data;
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (flag) {
                            getAllRelatedRegion(largeId, flexboxLayout);
                            DataApplication.classificationAndImageQualityFlag = false;
                        } else {
                            ToastUtil.show(context, "删除失败");
                        }
                    }
                });
            }
        });
    }

    //获取所有地区
    private void getAllRegion(List<TheRegion> rdatas, LinearLayout layout, List<CheckBox> checkBoxes, TextView textView) {
        httpModel.getAllRegion(data -> {
            List<TheRegion> datas = Utils.<TheRegion>objectToList(data);
            Iterator<TheRegion> iterator = datas.iterator();
            while (iterator.hasNext()) {
                TheRegion oneData = iterator.next();
                for (TheRegion rdata : rdatas) {
                    if (Objects.equals(rdata.getTheRegion(), oneData.getTheRegion())) {
                        iterator.remove();
                    }
                }
            }
            ContextThemeWrapper contextThemeWrapper = new ContextThemeWrapper(context, R.style.CheckBox);
            HttpClient.handler.post(new Runnable() {
                @Override
                public void run() {
                    if (datas.size() == 0) {
                        textView.setVisibility(View.VISIBLE);
                    }
                    for (TheRegion theRegion : datas) {
                        CheckBox checkBox = new CheckBox(contextThemeWrapper);
                        checkBox.setText(theRegion.getTheRegion());
                        checkBox.setId(theRegion.getId());
                        checkBoxes.add(checkBox);
                        layout.addView(checkBox);
                    }
                }
            });
        });
    }

    //给指定大分类添加指定年份的关联
    public void addYearRelation(FlexboxLayout flexboxLayout, int largeId, int yearId) {
        httpModel.addYearRelation(largeId, yearId, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Boolean flag = (Boolean) data;
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (flag) {
                            getAllRelatedYear(largeId, flexboxLayout);
                            DataApplication.classificationAndImageQualityFlag = false;
                        } else {
                            ToastUtil.show(context, "添加失败");
                        }
                    }
                });
            }
        });
    }

    //删除指定大分类和年份的关联
    public void deleteYearRelation(int largeId, int yearId, FlexboxLayout flexboxLayout) {
        httpModel.deleteYearRelation(largeId, yearId, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Boolean flag = (Boolean) data;
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (flag) {
                            getAllRelatedYear(largeId, flexboxLayout);
                            DataApplication.classificationAndImageQualityFlag = false;
                        } else {
                            ToastUtil.show(context, "删除失败");
                        }
                    }
                });
            }
        });
    }

    //获取所有年份
    private void getAllYear(List<TheYear> rdatas, LinearLayout layout, List<CheckBox> checkBoxes, TextView textView) {
        httpModel.getAllYear(data -> {
            List<TheYear> datas = Utils.<TheYear>objectToList(data);
            Iterator<TheYear> iterator = datas.iterator();
            while (iterator.hasNext()) {
                TheYear oneData = iterator.next();
                for (TheYear rdata : rdatas) {
                    if (Objects.equals(rdata.getTheYear(), oneData.getTheYear())) {
                        iterator.remove();
                    }
                }
            }
            ContextThemeWrapper contextThemeWrapper = new ContextThemeWrapper(context, R.style.CheckBox);
            HttpClient.handler.post(new Runnable() {
                @Override
                public void run() {
                    if (datas.size() == 0) {
                        textView.setVisibility(View.VISIBLE);
                    }
                    for (TheYear theYear : datas) {
                        CheckBox checkBox = new CheckBox(contextThemeWrapper);
                        checkBox.setText(theYear.getTheYear());
                        checkBox.setId(theYear.getId());
                        checkBoxes.add(checkBox);
                        layout.addView(checkBox);
                    }
                }
            });
        });
    }
}
